package HDFS;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

//HDFS常用文件相关类
public class HDFSApp {
    public static final String HDFS_PATH = "hdfs://192.168.7.100:9000";

    private Configuration con = null;
    private String linkUser = "root";

    private FileSystem fileSystem = null;

    @Before
    public void before() throws URISyntaxException, IOException, InterruptedException {
        con = new Configuration();

        fileSystem = FileSystem.get(new URI(HDFS_PATH),con,linkUser);
    }

    @After
    public void after() throws IOException {
        fileSystem.close();
    }

    /**
     * 创建目录
     * @throws IOException
     */
    @Test
    public void mkdir() throws IOException {
        fileSystem.mkdirs(new Path("/hdfsapi/test"));
    }

    /**
     * 创建文件
     * @throws IOException
     */
    @Test
    public void makefile() throws IOException {
        FSDataOutputStream fsDataOutputStream = fileSystem.create(new Path("/hdfsapi/test/a.txt"));

        fsDataOutputStream.write("hello world".getBytes());
        fsDataOutputStream.flush();
        fsDataOutputStream.close();
    }


    /**
     * 更改文件名称
     * @throws IOException
     */
    @Test
    public void rename() throws IOException {
         Path oldPath = new Path("/hdfsapi/test/a.txt");
         Path newPath = new Path("hdfsapi/test/dianzi.txt");
         fileSystem.rename(oldPath,newPath);
    }


    /**
     * 上传本地文件到hdfs
     * @throws IOException
     */
    @Test
    public void copyFromLocal() throws IOException {
        Path src = new Path("D:/cptest.txt");
        Path des = new Path("/hdfsapi/test");
        fileSystem.copyFromLocalFile(src,des);
    }

    /**
     * 查看某个目录下所有的文件
     * @throws IOException
     */
    @Test
    public void listfiles() throws IOException {
        FileStatus[] fileStatuses = fileSystem.listStatus(new Path("/hdfsapi/test/"));

        for(FileStatus fileStatus : fileStatuses){
            //文件属性
            String idDir = fileStatus.isDirectory()?"Dir" : "File";
            //权限
            String Permission = fileStatus.getPermission().toString();
            //副本系数
            short replication = fileStatus.getReplication();
            //长度
            long len = fileStatus.getLen();
            //路径
            Path path = fileStatus.getPath();

            System.out.println(idDir+"\t"
                                +Permission+"\t"
                                +replication+"\t"
                                +len+"\t"
                                +path);
        }
    }

}
